import { createStore } from "vuex";
import vuexPersist from "vuex-persist";
export default createStore({
  state: {
    shopcar: [],
    checked: false,
  },
  mutations: {
    add(state, val) {
      let flag = false;
      //代表购物车中有没有这个商品
      state.shopcar.forEach((item) => {
        if (item._id == val._id) {
          flag = true;
          item.num++;
        }
      });

      if (flag == false) {
        val.num = 1;
        //给一个初始的num为1
        val.status = false;
        //表示是否选中的状态
        state.shopcar.push(val);
      }
    },
    //添加购物车
    changeStatus(state) {
      // every
      state.checked = state.shopcar.every((item) => {
        return item.status == true;
      });
      //如果购物车中所有的商品的status都为true 那么checked全选按钮就为true 只要有一个是false那么就是false

      // 用filter实现
      // let res = state.shopcar.filter((item) => {
      //   return item.status == true;
      // });

      // if (res.length == state.shopcar.length) {
      //   state.checked = true;
      // } else {
      //   state.checked = false;
      // }
      // 用some实现
      // let res = state.shopcar.some((item) => {
      //   return item.status == false;
      // });
      // if (res == true) {
      //   state.checked = false;
      // } else {
      //   state.checked = true;
      // }
    },
    //点击上面的复选框

    checkAll(state) {
      state.shopcar.forEach((item) => {
        item.status = state.checked;
      });
      //循环让 购物车的每个商品的状态就等于 全选按钮的状态
    },
    del(state) {
      state.shopcar = state.shopcar.filter((item) => {
        return item.status == false;
      });
    },
    //选中删除 把不删的留下来
  },
  actions: {},
  modules: {},
  getters: {
    allPrice(state) {
      let all = 0;
      state.shopcar.forEach((item) => {
        if (item.status == true) {
          all += item.num * item.price;
        }
      });
      return all;
    },
    //计算总价
  },

  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
});
